import React from 'react';
import { useEffect, useState } from 'react';

import { Card, Button, Table, Modal, Form, Input, Upload, message, Popconfirm } from 'antd';
import { PlusOutlined, DeleteOutlined, FormOutlined, LoadingOutlined } from '@ant-design/icons';
import { getTradeListRes, addTradeRes, deleteTradeRes } from "@/api/product/trademark";
import type { UploadChangeParam } from 'antd/es/upload';
import type { RcFile, UploadFile, UploadProps } from 'antd/es/upload/interface';



export default function Trademark() {

    let [tradeList, setTradeList] = useState([]);
    let [total, setTotal] = useState(0);
    let [page, setPage] = useState(1);
    let [limit, setLimit] = useState(3);
    const [isModalOpen, setIsModalOpen] = useState<any>(false);
    const [loading, setLoading] = useState(false);
    const [imageUrl, setImageUrl] = useState<string>();
    const [form] = Form.useForm();
    const [id, setId] = useState("");

    const showModal = () => {
        setIsModalOpen(true);
        form.resetFields();
        setImageUrl("");
        setId("");



    };

    // 保存按钮
    function save() {
        // console.log(form.getFieldsValue());
        // console.log(form.getFieldValue("tmName"));
        let data: any = form.getFieldsValue();
        data.logoUrl = imageUrl;
        data.id = id;
        // console.log(data);

        form.validateFields().then(async value => {
            console.log("value", value);
            try {

                await addTradeRes(data);
                setIsModalOpen(false);

                if (data.id) {

                    console.log("修改");
                    getTradeList(page, limit);
                    message.success("修改成功")
                } else {
                    setPage(1);
                    console.log("添加");
                    getTradeList(1, limit);
                    message.success("添加成功")
                }
                setImageUrl("");
                setId("");

            } catch (error) {
                message.error(data.id ? "修改失败" : "添加失败")
            }

        })




    }
    // 更新按钮
    function editBtn(data: any) {
        form.setFieldsValue(data);
        setImageUrl(data.logoUrl);
        setId(data.id)
        setIsModalOpen(true);
    }

    const confirm = (data: any) => {
        return async function (e: any) {
            try {
                await deleteTradeRes(data.id);
                getTradeList(page, limit);
                message.success("删除成功")
            } catch (error) {
                message.error("删除失败")
            }
        }
    };

    const cancel = (e: React.MouseEvent<HTMLElement>) => {
        console.log(e);
        message.error('Click on No');
    };



    async function getTradeList(page: number, limit: number) {
        let result = await getTradeListRes(page, limit);
        setTradeList(result.records);
        setTotal(result.total)
    }

    useEffect(() => {
        getTradeList(page, limit);
    }, [])

    const columns: any = [
        {
            title: "序号",
            render: (txt: any, records: any, index: any) => {
                // console.log(txt, records, "列");
                return index + 1
            },
            width: 80,
            align: "center"
        },
        {
            title: "品牌名称",
            dataIndex: "tmName",
            align: "center"
        },
        {
            title: "品牌LOGO",
            // 当前这一行的信息
            render: (data: any) => {
                return (
                    <>
                        <img src={data.logoUrl} alt="" style={{ width: 80, height: 60 }} />
                    </>
                )
            },
            align: "center"
        },
        {
            title: "品牌操作",
            render: (data: any) => {
                return (
                    <>
                        <Button type='primary' icon={<FormOutlined />} style={{ marginRight: 20 }} onClick={() => editBtn(data)}></Button>

                        <Popconfirm
                            title={`是否确认删除 ${data.tmName} ？`}
                            onConfirm={confirm(data)}

                            okText="确定"
                            cancelText="取消"
                        >
                            <Button type='primary' danger icon={<DeleteOutlined />}></Button>
                        </Popconfirm>
                    </>
                )
            },
            align: "center"
        },
    ]



    const beforeUpload = (file: RcFile) => {
        // console.log(file);

        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === "image/gif";
        if (!isJpgOrPng) {
            message.error('请上传 jpeg/png/gif 图片!');
        }
        const isLt2M = file.size / 1024 / 1024 < 5;
        if (!isLt2M) {
            message.error('图片大小不能超过5M!');
        }
        return isJpgOrPng && isLt2M;
    };




    const handleChange: UploadProps['onChange'] = (info: UploadChangeParam<UploadFile>) => {
        console.log("change", info);

        if (info.file.status === 'uploading') {
            setLoading(true);
            return;
        }
        if (info.file.status === 'done') {
            console.log(info, "info");
            setImageUrl(info.file.response.data);
            setLoading(false);
        }
    };

    const uploadButton = (
        <div>
            {loading ? <LoadingOutlined /> : <PlusOutlined />}
            <div style={{ marginTop: 8 }}>Upload</div>
        </div>
    );

    const normFile = (e: any) => {
        console.log('Upload event:', e);
        if (Array.isArray(e)) {
          return e;
        }
        return e?.fileList;
      };


    return (
        <div>
            <Card>
                <Button type="primary" icon={<PlusOutlined />} onClick={showModal}>添加</Button>

                {/* 添加品牌时的对话框 */}
                {/* 对话框  小于4版本的是使用visible  其他用open */}
                <Modal title={id?"修改品牌":"添加品牌"} visible={isModalOpen} onOk={save} onCancel={() => { setIsModalOpen(false) }}>
                    <Form labelCol={{ span: 5 }} wrapperCol={{ span: 16 }} form={form}>
                        <Form.Item label="品牌名称" name="tmName" rules={[{ required: true, message: "请输入品牌名称" }, { min: 2, max: 10, message: "品牌名称控制在2到10个字符！" }]}>
                            <Input></Input>
                        </Form.Item>
                        <Form.Item label="品牌LOGO" name="logoUrl" rules={[{ required: true, message: "请上传图片" }]}>
                            <Upload
                                // 发到后台的文件参数名  要想拿到图片的路径需要name属性为file
                                name="file"

                                listType="picture-card"
                                className="avatar-uploader"
                                showUploadList={false}
                                // valuePropName="fileList"
                                // getValueFromEvent={normFile}
                                action="/dev-api/admin/product/upload"
                                beforeUpload={beforeUpload}
                                onChange={handleChange}
                                // getValueFromEvent={normFile}
                            >
                                {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%', height: "100%" }} /> : uploadButton}
                            </Upload>
                        </Form.Item>
                    </Form>
                </Modal>

                <Table dataSource={tradeList} columns={columns} bordered style={{ margin: "20px 0" }}
                    rowKey="id"
                    pagination={{
                        total,
                        pageSize: limit,
                        current: page,
                        pageSizeOptions: [3, 5, 7],
                        showQuickJumper: true,
                        showSizeChanger: true,
                        onChange: (page, pageSize) => {
                            setPage(page);
                            setLimit(pageSize);
                            getTradeList(page, pageSize);
                        },
                        showTotal: (total) => {
                            return `总共${total}条`
                        }
                    }}>

                </Table>

            </Card>
        </div>
    )
}